<template>
  <div class="main">
    <Layout class="layout-wrapper">
      <Sider collapsible v-show="wiindowSize !== 'xs' && wiindowSize !== 'sm'" hide-trigger v-model="collapsed" collapsed-width="74">
        <SiderMenu :active-name="$route.name" :collapsed="collapsed" :list="menuList" @on-select="handleSelect">
          <template v-slot:siderLogo>
            <div class="sider-logo">
              <h2 v-if="collapsed">T</h2>
              <h2 v-else>TPSHION ADMIN</h2>
            </div>
          </template>
        </SiderMenu>
      </Sider>
      <div class="mobile-menu" v-show="wiindowSize === 'xs' || wiindowSize === 'sm'">
        <Drawer :closable="false" v-model="mobile" placement="left">
          <Menu width="auto" theme="dark" @on-select="handleSelect">
            <template v-for="item in menuList">
              <SiderSubmenu
                v-if="item.children"
                :key="`menu_${item.name}`"
                :name="item.name"
                :parent="item"
              >
              </SiderSubmenu>
              <MenuItem v-else :key="`menu_${item.name}`" :name="item.name">
                <Icon :type="item.icon" :size="23" />
                {{item.title}}
              </MenuItem>
            </template>
          </Menu>
        </Drawer>
      </div>
      <Layout>
        <Header class="header-wrapper">
          <Row :gutter="10" class="hearder-row" v-show="wiindowSize !== 'xs' && wiindowSize !== 'sm'" :style="{paddingRight: headerTrigger}">
            <Col span="1">
              <Icon :class="triggerClasses" @click.native="handleCollapsed" type="md-menu" :size="23" />
            </Col>
            <Col span="15">
              <Breadcrumb v-show="wiindowSize !== 'xs' && wiindowSize !== 'sm' && wiindowSize !== 'md'">
                <BreadcrumbItem>
                    <Icon type="ios-home-outline"></Icon> 首页
                </BreadcrumbItem>
                <BreadcrumbItem v-for="item in breadList" :key="`bread_${item.name}`">
                  <Icon :type="item.icon"></Icon> {{item.title}}
                </BreadcrumbItem>
              </Breadcrumb>
            </Col>
            <Col span="23" v-show="wiindowSize === 'md'">
              <Row type="flex" justify="end">
                <Col :span="2">
                  <Dropdown transfer trigger="click" @on-click="handleUserClick">
                    <Avatar size="large" :src="userInfo.userImg" :style="{cursor: 'pointer'}">{{userInfo.username}}</Avatar>
                    <DropdownMenu slot="list">
                      <DropdownItem name="userInfo">个人中心</DropdownItem>
                      <DropdownItem name="logout">退出登录</DropdownItem>
                    </DropdownMenu>
                  </Dropdown>
                </Col>
              </Row>
            </Col>
            <Col span="8" v-show="wiindowSize === 'lg' || wiindowSize === 'xl' || wiindowSize === 'xxl'">
              <Row type="flex" justify="end">
                <Col :span="2">
                  <Dropdown transfer @on-click="handleUserClick">
                    <Avatar size="large" :src="userInfo.userImg" :style="{cursor: 'pointer'}">{{userInfo.username}}</Avatar>
                    <DropdownMenu slot="list">
                      <DropdownItem name="userInfo">个人中心</DropdownItem>
                      <DropdownItem name="logout">退出登录</DropdownItem>
                    </DropdownMenu>
                  </Dropdown>
                </Col>
              </Row>
            </Col>
          </Row>
          <Row :gutter="10" v-show="wiindowSize === 'xs' || wiindowSize === 'sm'">
            <Col span="1">
              <Icon class="header-icon-height" @click.native="handleMobileCollapsed" type="md-menu" :size="23" />
            </Col>
            <Col span="19">
              <div class="sider-logo-mobile">
                <h3>TPSHION ADMIN</h3>
              </div>
            </Col>
            <Col span="1">
              <Dropdown transfer trigger="click" @on-click="handleUserClick">
                <Avatar :src="userInfo.userImg" :style="{cursor: 'pointer'}">{{userInfo.username}}</Avatar>
                <DropdownMenu slot="list">
                  <DropdownItem name="userInfo">个人中心</DropdownItem>
                  <DropdownItem name="logout">退出登录</DropdownItem>
                </DropdownMenu>
              </Dropdown>
            </Col>
          </Row>
        </Header>
        <Content class="content-wrapper">
          <Card class="page-card" :dis-hover="true" :bordered="false">
            <Row class="nav-tag-row"
              :style="{width: navTrigger}"
              v-show="wiindowSize === 'md' || wiindowSize === 'lg' || wiindowSize === 'xl' || wiindowSize === 'xxl'"
            >
              <Col :span="23" class="nav-tag-content">
                <Tag
                  @on-close="handleTagClose"
                  :name="item.name" type="dot" closable
                  :color="item.name == $route.name ? 'primary' : 'default'"
                  v-for="item in navList"
                  :key="`tag_${item.name}`"
                  @click.native="handleTagClick(item.name)"
                  :style="{cursor: 'pointer'}"
                >
                  {{item.title}}
                </Tag>
              </Col>
              <Col :span="1" class="nav-tag-height-right">
                <Button shape="circle" v-show="navList.length > 0" icon="md-close" @click="handleCloseNav"></Button>
              </Col>
            </Row>
            <Card :dis-hover="true" class="page-card-content" :style="{marginTop: pageCardTrigger}">
              <router-view v-show="$route.name !== 'main'"/>
              <div v-show="$route.name === 'main'">
                <!-- 加载等待 -->
                <Spin fix v-show="show">
                    <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
                    <div>加载中...</div>
                </Spin>
                <div class="content-header">
                  <Card :dis-hover="true">
                    <div class="header-title">
                      <h3>{{userInfo.username + '，'}}开始您一天的工作吧！</h3>
                    </div>
                    <div class="header-text">
                      <p> 永远相信，美好的事情即将发生！</p>
                    </div>
                  </Card>
                </div>
                <Row :gutter="16">
                  <Col :xs="24" :sm="24" :md="6" :lg="6">
                    <Card class="tool-card" style="border-color: rgb(64, 169, 255)">
                      <Avatar icon="ios-people" style="color: rgb(64, 169, 255); background-color: rgb(230, 247, 255);"/>
                      <h1>{{reqNum}}</h1>
                      <p>访问次数</p>
                    </Card>
                  </Col>
                  <Col :xs="24" :sm="24" :md="6" :lg="6">
                    <Card class="tool-card" style="border-color: rgb(146, 84, 222)">
                      <Avatar icon="ios-locate" style="color: rgb(146, 84, 222); background-color: rgb(249, 240, 255);"/>
                      <h1>100G</h1>
                      <p>磁盘容量</p>
                    </Card>
                  </Col>
                  <Col :xs="24" :sm="24" :md="6" :lg="6">
                    <Card class="tool-card" style="border-color: rgb(255, 169, 64)">
                      <Avatar icon="ios-paper-plane" style="color: rgb(255, 169, 64); background-color: rgb(255, 247, 230);"/>
                      <h1>{{discovery.size}}</h1>
                      <p>实例服务</p>
                    </Card>
                  </Col>
                  <Col :xs="24" :sm="24" :md="6" :lg="6">
                    <Card class="tool-card" style="border-color: rgb(115, 209, 61)">
                      <Avatar icon="ios-alert" style="color: rgb(115, 209, 61); background-color: rgb(246, 255, 237);"/>
                      <h1>20</h1>
                      <p>待办事项</p>
                    </Card>
                  </Col>
                </Row>

                <Row :gutter="16">
                  <Col :xs="24" :sm="24" :md="12" :lg="12" style="margin-bottom: 10px;">
                    <Card :dis-hover="true">
                      <div slot="title">
                        <Avatar size="small" icon="md-apps" style="color: rgb(24, 144, 255); background-color: rgb(230, 247, 255);"/>
                        我的项目
                      </div>
                      <a href="#" slot="extra">
                        <Icon type="ios-loop-strong"></Icon>
                        全部项目
                      </a>
                      <div style="padding: 16px;height: 300px; overflow: auto;">
                        <Timeline>
                          <TimelineItem color="green">发布1.0版本</TimelineItem>
                          <TimelineItem color="green">发布2.0版本</TimelineItem>
                          <TimelineItem color="red">严重故障</TimelineItem>
                          <TimelineItem color="blue">发布3.0版本</TimelineItem>
                          <TimelineItem><a href="#">查看更多</a></TimelineItem>
                        </Timeline>
                      </div>
                    </Card>
                  </Col>
                  <Col :xs="24" :sm="24" :md="12" :lg="12" style="margin-bottom: 10px;">
                    <Card :dis-hover="true">
                      <div slot="title">
                        <Avatar size="small" icon="ios-chatbubbles" style="color: rgb(24, 144, 255); background-color: rgb(230, 247, 255);"/>
                        我的消息
                      </div>
                      <a href="#" slot="extra">
                        <Icon type="ios-loop-strong"></Icon>
                        全部消息
                      </a>
                      <div style="padding: 16px; height: 300px; overflow: auto;">
                        <List>
                          <ListItem>
                            <ListItemMeta
                              avatar="https://dev-file.iviewui.com/userinfoPDvn9gKWYihR24SpgC319vXY8qniCqj4/avatar"
                              title="测试消息"
                              description="这是一条测试消息"
                            />
                            <template slot="action">
                              <li>
                                <a href="">查看</a>
                              </li>
                              <li>
                                <a href="" style="color: red;">删除</a>
                              </li>
                            </template>
                          </ListItem>
                          <ListItem>
                            <ListItemMeta
                              avatar="https://dev-file.iviewui.com/userinfoPDvn9gKWYihR24SpgC319vXY8qniCqj4/avatar"
                              title="测试消息"
                              description="这是一条测试消息"
                            />
                            <template slot="action">
                              <li>
                                <a href="">查看</a>
                              </li>
                              <li>
                                <a href="" style="color: red;">删除</a>
                              </li>
                            </template>
                          </ListItem>
                          <ListItem>
                            <ListItemMeta
                              avatar="https://dev-file.iviewui.com/userinfoPDvn9gKWYihR24SpgC319vXY8qniCqj4/avatar"
                              title="测试消息"
                              description="这是一条测试消息"
                            />
                            <template slot="action">
                              <li>
                                <a href="">查看</a>
                              </li>
                              <li>
                                <a href="" style="color: red;">删除</a>
                              </li>
                            </template>
                          </ListItem>
                          <ListItem>
                            <ListItemMeta
                              avatar="https://dev-file.iviewui.com/userinfoPDvn9gKWYihR24SpgC319vXY8qniCqj4/avatar"
                              title="测试消息"
                              description="这是一条测试消息"
                            />
                            <template slot="action">
                              <li>
                                <a href="">查看</a>
                              </li>
                              <li>
                                <a href="" style="color: red;">删除</a>
                              </li>
                            </template>
                          </ListItem>
                          <ListItem>
                            <ListItemMeta
                              avatar="https://dev-file.iviewui.com/userinfoPDvn9gKWYihR24SpgC319vXY8qniCqj4/avatar"
                              title="测试消息"
                              description="这是一条测试消息"
                            />
                            <template slot="action">
                              <li>
                                <a href="">查看</a>
                              </li>
                              <li>
                                <a href="" style="color: red;">删除</a>
                              </li>
                            </template>
                          </ListItem>
                        </List>
                      </div>
                    </Card>
                  </Col>
                </Row>
              </div>
            </Card>
          </Card>
          <Footer class="footer-wrapper">2019-2020 &copy; TPSHION</Footer>
        </Content>
      </Layout>
    </Layout>
  </div>
</template>

<script>
import SiderMenu from '_c/sider-menu'
import SiderSubmenu from '_c/sider-menu/SiderSubmenu.vue'
import {defaultMenu} from '@/utils/constants'
import {getUserInfo,logout, getMenuTree} from '@/api/user'
import {setSessionStore,getSessionStore,removeSessionStore,setStoreByJson,getStoreByJson} from '@/utils/storeUtil'
import {checkNavList} from '@/utils/commonUtil'
import {getAllService,getRequstNum} from '@/api/base'

export default {
  name: 'Main',
  components:{
    SiderMenu,
    SiderSubmenu
  },
  data(){
    return {
      fullWidth: document.documentElement.clientWidth,
      fullHeight: document.documentElement.clientHeight,
      collapsed: false,
      mobile: false,
      breadList: [],
      menuList: [],
      navList: [],
      userInfo: ()=> ({}),
      discovery: {
        services: [],
        size: 0
      },
      reqNum: 0,
      show: true,
    }
  },
  computed:{
    /**
     * 左侧菜单按钮旋转
     */
    triggerClasses(){
      return ['trigger-icon', this.collapsed ? 'rotate' : '', 'header-icon-height']
    },
    /**
     * 动态计算浏览器窗口大小
     * xs: '480px',
     * sm: '576px',
     * md: '768px',
     * lg: '992px',
     * xl: '1200px',
     * xxl: '1600px'
     */
    wiindowSize() {
      if(this.fullWidth >= 0 && this.fullWidth <= 480){
        return 'xs'
      }else if(this.fullWidth > 480 && this.fullWidth <= 576){
        return 'sm'
      }else if(this.fullWidth > 576 && this.fullWidth <= 768){
        return 'md'
      }else if(this.fullWidth > 768 && this.fullWidth <= 992){
        return 'lg'
      }else if(this.fullWidth > 992 && this.fullWidth <= 1200){
        return 'xl'
      }else if(this.fullWidth > 1200){
        return 'xxl'
      }
    },
    /**
     * 动态计算header padding补充
     */
    headerTrigger(){
      return this.collapsed ? '136px' : '200px'
    },
    navTrigger(){
      return this.collapsed ? 'calc(100vw - 95px)' : 'calc(100vw - 223px)'
    },
    pageCardTrigger(){
      if(this.wiindowSize == 'xs' || this.wiindowSize == 'sm'){
        return '5px'
      }else{
        return '35px'
      }
    }
  },
  methods:{
    /**
     * 动态获取浏览器宽高
     */
    handleResize() {
      this.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = document.documentElement.clientHeight;
    },
    /**
     * 控制左侧菜单展开关闭
     */
    handleCollapsed(){
      this.collapsed = !this.collapsed
    },
    /**
     * 控制手机模式菜单展开关闭
     */
    handleMobileCollapsed(){
      this.mobile = !this.mobile
    },
    /**
     * 展开状态下获取菜单name
     */
    handleSelect(name){
      if(this.mobile) this.mobile = false
      console.log("菜单: name="+name)
      this.breadList = [];
      this.getMenuLev(this.menuList,name)

      // 判断name是否已存在
      if(!checkNavList(this.navList,name)){
        // 判断是否达到最大
        if(this.navList.length >= 20){
          this.navList[this.navList.length - 1] = this.breadList[this.breadList.length - 1]
        }else{
          // 不存在直接添加
          this.navList.push(this.breadList[this.breadList.length - 1])
        }
      }

      setSessionStore('navList',this.navList)
      this.$router.push({name:name})
    },
    /**
     * 获取菜单层级关系
     */
    getMenuLev(list,name){
      for(let i=0; i<list.length; i++){
        if(list[i].name === name){
          this.breadList.unshift({
            name: list[i].name,
            title: list[i].title,
            icon: list[i].icon
          })
          return
        }
        if(list[i].children){
          this.getMenuLev(list[i].children,name)
        }
      }
    },
    /**
     * 处理用户管理操作
     */
    handleUserClick(name){
      console.log("用户管理：name="+name)
      //退出登录
      if(name === 'logout'){
        logout().then(res=>{
          if(res.data.status){
            this.$store.commit('userLogout')
            removeSessionStore('navList')
            this.$router.push({name: 'login'})
          }
        })
      }
    },
    /**
     * 获取菜单数据
     */
    getMenuData(){
      getMenuTree({
        userId: this.$store.state.user.userInfo.userId,
        sysCode: 'tpshion-cloud-auth'
      }).then(res =>{
        if(res.data.status){
          this.menuList = res.data.data.menuTrees
          this.menuList.unshift(defaultMenu)
          let access = res.data.data.access
          access.push(defaultMenu.name)
          setStoreByJson('access',access)
          this.initNavTag()
        }
      })
    },
    /**
     * 关闭所有标签页
     */
    handleCloseNav(){
      //console.log("关闭所有标签页")
      this.$Modal.confirm({
        title: '确定关闭所有标签页吗？',
        onOk: () => {
          removeSessionStore('navList')
          this.breadList = []
          this.navList = []
          this.breadList.push(defaultMenu)
          this.navList.push(defaultMenu)
          setSessionStore('navList',this.navList)
          this.$router.push({name: defaultMenu.name})
        }
      })
    },
    /**
     * 关闭单个标签页
     */
    handleTagClose(event,name){
      //console.log("关闭标签："+name)
      if(this.navList.length == 1){
        //console.log('defaultMenu:',defaultMenu)
        this.breadList = []
        this.navList = []
        this.breadList.push(defaultMenu)
        this.navList.push(defaultMenu)
        setSessionStore('navList',this.navList)
        this.$router.push({name: defaultMenu.name})
      }else{
        this.navList.forEach((item,index, arr) =>{
          if(item.name == name){
            arr.splice(index, 1)
          }
        })

        this.breadList = [];
        let routeName = this.navList[this.navList.length - 1].name
        this.getMenuLev(this.menuList,routeName)
        setSessionStore('navList',this.navList)
        this.$router.push({name: routeName})
      }
    },
    /**
     * 标签切换路由
     */
    handleTagClick(name){
      this.$router.push({name:name})
      this.breadList = [];
      this.getMenuLev(this.menuList,name)
    },
    /**
     * 初始化标签
     */
    initNavTag(){
      console.log('name:',this.$route.name)
      console.log('path:',this.$route.path)
      if(this.$route.name === 'main'){
        let store = getSessionStore('navList')
        if(store && store[0] != null){
          this.breadList = []
          this.getMenuLev(this.menuList,'main')
          //this.navList = store
          let accessStore = getStoreByJson('access')
          store.forEach(item => {
            if(accessStore.indexOf(item.name) != -1){
              this.navList.push(item)
            }
          })
          setSessionStore('navList',this.navList)
        }else{
          this.breadList = []
          this.navList = []
          this.breadList.push(defaultMenu)
          this.navList.push(defaultMenu)
          setSessionStore('navList',this.navList)
        }
      }else{
        let store = getSessionStore('navList')
        if(store && store[0] != null){
          this.breadList = []
          this.getMenuLev(this.menuList,this.$route.name)
          let accessStore = getStoreByJson('access')
          store.forEach(item => {
            if(accessStore.indexOf(item.name) != -1){
              this.navList.push(item)
            }
          })
          setSessionStore('navList',this.navList)
          if(accessStore.indexOf(this.$route.name) == -1){
            this.$router.push({name: defaultMenu.name})
          }
        }else{
          this.breadList = []
          this.getMenuLev(this.menuList,this.$route.name)
          this.navList.push(this.breadList[this.breadList.length - 1])
          setSessionStore('navList',this.navList)
        }
      }
    },
    /**
     * 获取用户信息
     */
    initUserInfo(){
      getUserInfo(this.$store.state.user.userInfo.userId).then(res=>{
        if(res.data.status){
          this.userInfo = res.data.data
        }
      })
    },
    /**
     * 获取服务
     */
    initService(){
      getAllService().then(res => {
        if(res.data.status){
          this.discovery = res.data.data
        }
      })
    },
    /**
     * 获取访问次数
     */
    getRequestNum(){
      getRequstNum().then(res => {
        this.reqNum = res.data.data
      })
    },
  },
  created() {
    window.addEventListener("resize", this.handleResize)
    //获取菜单数据
    this.getMenuData()
    this.initUserInfo()
    this.initService()
    this.getRequestNum()
  },
  mounted(){
    this.show = false
  },
  beforeDestroy: function () {
    window.removeEventListener("resize", this.handleResize)
  }
}
</script>

<style lang="less">
.main, .layout-wrapper{
  height: 100%;
  .header-wrapper{
    position: fixed;
    width: 100%;
    background: #fff;
    box-shadow: 0 1px 1px 1px rgba(0,0,0,.1);
    padding: 0 23px;
    .trigger-icon{
      cursor: pointer;
      transition: transform .3s ease;
      &.rotate{
        transform: rotateZ(-90deg);
        transition: transform .3s ease;
      }
    }
    .ivu-breadcrumb{
      font-size: 17px;
    }
    .header-icon-height{
      line-height: 64px;
    }
    .hearder-row{
      transition: padding-right .3s ease;
    }
  }
  .sider-logo{
    height: 64px;
    width: 100%;
    text-align: center;
    line-height: 64px;
    color: #fff;
  }
  .sider-logo-mobile{
    height: 64px;
    width: 100%;
    text-align: center;
    line-height: 64px;
  }
  .content-wrapper{
    overflow: auto;
    margin-top: 64px;
    position: relative;
    .page-card{
      //min-height: ~"calc(100vh - 123px)";
      //min-height: 1000px;
      background: #f5f7f9;
      position: relative;
      .ivu-card-body{
        padding: 5px;
      }
      .nav-tag-row{
        height: 40px;
        position: fixed;
        top: 64px;
        right: 18px;
        transition: width .3s ease;
        z-index: 1000;
        padding-left: 1px;
        padding-right: 10px;
        background-color: #f5f7f9;
        .nav-tag-height-right{
          line-height: 34px;
          text-align: right;
        }
        .nav-tag-content{
          height: 39px;
          line-height: 39px;
          overflow-y: scroll;
        }
      }
      .page-card-content{
        //margin-top: 44px;
        min-height: ~"calc(100vh - 188px)";
        z-index: 10;
        .content-header{
          height: 100px;
          .header-title{
            padding: 10px;
          }
          .header-text{
            padding-left: 10px;
            padding-right: 10px;
            text-align: right;
          }
        }
        .tool-card{
          text-align: center;
          padding: 16px;
          margin-bottom: 10px;
        }
        .demo-spin-icon-load{
          animation: ani-demo-spin 1s linear infinite;
        }
      }
    }
  }
  .footer-wrapper{
    text-align: center;
  }
}
.ivu-drawer-wrap .ivu-drawer .ivu-drawer-content .ivu-drawer-body{
  padding: 0;
  background: #515a6e;
}
</style>
